package com.usian.user.service.impl;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.usian.common.dto.UserDto;
import com.usian.common.pojo.*;
import com.usian.common.vo.ResponseResult;
import com.usian.user.feign.*;
import com.usian.user.mapper.UserMapper;
import com.usian.user.service.IndexService;
import com.usian.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class IndexServiceImpl implements IndexService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CompetitionFeign competitionFeign;

    @Autowired
    private TrainFeign trainFeign;

    @Autowired
    private CourseFeign courseFeign;

    @Autowired
    private ExamFeign examFeign;

    public static void main(String[] args) {
        Map<String, Object> payload = new HashMap<>();
        payload.put("userId", 1);
        String token = JWTUtil.createToken(payload, "123".getBytes());
        log.info("=============:{}", token);
        JWT jwt = JWTUtil.parseToken(token);
        Integer userId = (Integer) jwt.getPayload("userId");
        log.info("=============:{}", userId);
    }


    @Override
    public ResponseResult myCompetition(String token) {
        if (token == null) {
            return ResponseResult.errorResult("请登录");
        }
        JWT jwt = JWTUtil.parseToken(token);
        Integer userId = (Integer) jwt.getPayload("userId");
        Compe competitionNum = competitionFeign.getCompetitionCounts(userId);
        return ResponseResult.okResult(competitionNum);
    }

    @Override
    public ResponseResult myTrain(String token) {
        if (token == null) {
            return ResponseResult.errorResult("请登录");
        }
        JWT jwt = JWTUtil.parseToken(token);
        Integer userId = (Integer) jwt.getPayload("userId");
        Train trainNums = trainFeign.getTrainCounts(userId);
        return ResponseResult.okResult(trainNums);
    }

    @Override
    public ResponseResult myCourse(String token) {
        if (token == null) {
            return ResponseResult.errorResult("请登录");
        }
        JWT jwt = JWTUtil.parseToken(token);
        Integer userId = (Integer) jwt.getPayload("userId");
        Cou cou = courseFeign.getTrainCourse(userId);
        return ResponseResult.okResult(cou);
    }

    @Override
    public ResponseResult hotCourse() {
        List<Cou> hotCourse = courseFeign.getHotCourse();
        log.info("=========:{}",hotCourse);
        return ResponseResult.okResult(hotCourse);
    }

    public String getLikeKey(String userId,String courseId){
        StringBuilder builder = new StringBuilder();
        builder.append(courseId);
        builder.append("::");
        builder.append(userId);
        String key = builder.toString();
        return key;
    }

    public ResponseResult like(String userId,String courseId) {
        Integer count = (Integer) redisTemplate.opsForHash().get("COURSE_LIKE_COUNT", courseId);
        if (count==null){
            return ResponseResult.errorResult("服务器错误");
        }
        count++;
        redisTemplate.opsForHash().put("COURSE_LIKE_COUNT",courseId,count);
//        redisTemplate.opsForHash().increment("COURSE_LIKE_COUNT",id,1);
        String likeKey = getLikeKey(userId, courseId);
        //用户已点赞
        redisTemplate.opsForHash().put("USER_COURSE_LIKE",likeKey,1);
        return ResponseResult.okResult("点赞成功");
    }

    public ResponseResult unlike(String userId, String courseId) {
        Integer count = (Integer) redisTemplate.opsForHash().get("COURSE_LIKE_COUNT", courseId);
        if (count==null){
            return ResponseResult.errorResult("服务器错误");
        }
        count--;
        redisTemplate.opsForHash().put("COURSE_LIKE_COUNT",courseId,count);
        String likeKey = getLikeKey(userId, courseId);
        Boolean hasKey = redisTemplate.opsForHash().hasKey("USER_COURSE_LIKE",likeKey);
        if (!hasKey){
            return ResponseResult.errorResult("服务器错误");
        }
        redisTemplate.opsForHash().delete("USER_COURSE_LIKE",likeKey);
        return ResponseResult.okResult("取消点赞成功");
    }

    @Override
    public ResponseResult haslike(String token, Integer id) {
        if (token == null) {
            return ResponseResult.errorResult("请登录");
        }
        JWT jwt = JWTUtil.parseToken(token);
        Integer tokenId = (Integer) jwt.getPayload("userId");
        String userId = String.valueOf(tokenId);
        String courseId = String.valueOf(id);
        Boolean hasKey = redisTemplate.opsForHash().hasKey("USER_COURSE_LIKE", getLikeKey(userId, courseId));
        if (hasKey){
            this.unlike(userId,courseId);
            return ResponseResult.okResult("取消点赞");
        }else {
            this.like(userId,courseId);
            return ResponseResult.okResult("点赞成功");
        }
    }

    @Override
    public ResponseResult getNewestClass() {
        List<Cou> classList = courseFeign.getNewestClass();
        return ResponseResult.okResult(classList);
    }

    @Override
    public ResponseResult hasNewestLike(String token, Integer id) {
        if (token == null) {
            return ResponseResult.errorResult("请登录");
        }
        JWT jwt = JWTUtil.parseToken(token);
        Integer tokenId = (Integer) jwt.getPayload("userId");
        String userId = String.valueOf(tokenId);
        String courseId = String.valueOf(id);
        Boolean hasKey = redisTemplate.opsForHash().hasKey("USER_NEWEST_COURSE_LIKE", getLikeKey(userId, courseId));
        if (hasKey){
            this.unNewestlike(userId,courseId);
            return ResponseResult.okResult("取消点赞");
        }else {
            this.newestLike(userId,courseId);
            return ResponseResult.okResult("点赞成功");
        }
    }

    @Override
    public ResponseResult getNewestTrain() {
        List<NewTrain> trainList = trainFeign.getNewestTrain();
        return ResponseResult.okResult(trainList);
    }

    @Override
    public ResponseResult getNewestExam() {
        List<Sj> examList = examFeign.getNewestExam();
        return ResponseResult.okResult(examList);
    }

    public ResponseResult unNewestlike(String userId, String courseId) {
        Integer count = (Integer) redisTemplate.opsForHash().get("NEWEST_COURSE_COUNT", courseId);
        if (count==null){
            return ResponseResult.errorResult("服务器错误");
        }
        count = count-1;
        redisTemplate.opsForHash().put("NEWEST_COURSE_COUNT",courseId,count);
        String likeKey = getLikeKey(userId, courseId);
        Boolean hasKey = redisTemplate.opsForHash().hasKey("USER_NEWEST_COURSE_LIKE",likeKey);
        if (!hasKey){
            return ResponseResult.errorResult("服务器错误");
        }
        redisTemplate.opsForHash().delete("USER_NEWEST_COURSE_LIKE",likeKey);
        return ResponseResult.okResult("取消点赞成功");
    }

    public ResponseResult newestLike(String userId, String courseId) {
        Integer count = (Integer) redisTemplate.opsForHash().get("NEWEST_COURSE_COUNT", courseId);
        if (count==null){
            return ResponseResult.errorResult("服务器错误");
        }
        count++;
        redisTemplate.opsForHash().put("NEWEST_COURSE_COUNT",courseId,count);
        //redisTemplate.opsForHash().increment("NEWEST_COURSE_COUNT",courseId,1);
        String likeKey = getLikeKey(userId, courseId);
        //用户已点赞
        redisTemplate.opsForHash().put("USER_NEWEST_COURSE_LIKE",likeKey,1);
        return ResponseResult.okResult("点赞成功");
    }
}
